package com.dorsica.dbupdate;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.h2.Driver;

/**
 * Parent mojo containing global parameters for all mojos
 * 
 * @author jessica
 * 
 */
public abstract class DbUpdateAbstractMojo extends AbstractMojo {

    @Parameter(defaultValue = "DBHISTORY")
    protected String tableName;

    @Parameter(required = true)
    protected String driver;

    @Parameter
    protected String url;

    @Parameter
    protected String user;

    @Parameter
    protected String password;

    @Parameter
    protected String rootUpdateDir;

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRootUpdateDir() {
        return rootUpdateDir;
    }

    public void setRootUpdateDir(String rootUpdateDir) {
        this.rootUpdateDir = rootUpdateDir;
    }

    protected boolean doesTableExists(String tableName) throws SQLException {
        try (Connection c = dbConnect()) {

            ResultSet rs = c.getMetaData().getTables(null, null, tableName,
                    null);
            int cpt = 0;
            while (rs.next()) {
                cpt++;
            }

            return cpt == 1;

        }
    }

    protected Connection dbConnect() throws SQLException {
        try {
            Class<?> dc = Class.forName(driver);
            Driver driverInstance = (Driver) dc.newInstance();

            Properties props = new Properties();
            props.setProperty("user", user);
            props.setProperty("password", password);

            return driverInstance.connect(url, props);
        } catch (ClassNotFoundException | InstantiationException
                | IllegalAccessException e) {
            throw new SQLException(e);
        }
    }
}
